/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * gui.java
 *
 * Created on 06.apr.2010, 14:42:38
 */

package towerdefencegame;

import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JPanel;
import javax.swing.UIManager;

import creep.Creep;


/**
 *
 * @author Haaland
 */
@SuppressWarnings("serial")
public class Gui extends javax.swing.JFrame implements constantsUsed {

    /** Creates new form gui */
    public Gui() {
        try {
	        UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
	        }  catch(Exception e) {};
	        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    private void initComponents() { 	
            	   mainPanel = new mainPanel();

        tornPanel = new javax.swing.JPanel();
        toggleTower1 = new javax.swing.JToggleButton();
        toggleTower2 = new javax.swing.JToggleButton();
        toggleTower3 = new javax.swing.JToggleButton();
        toggleTower4 = new javax.swing.JToggleButton();
        toggleTower5 = new javax.swing.JToggleButton();
        toggleTower6 = new javax.swing.JToggleButton();
        selectedTower = null;
      
     
        rightInfoPanel = new javax.swing.JPanel();
        detailsLabel = new javax.swing.JLabel();
        inGameButtonPanel = new javax.swing.JPanel();
        buttonNextWave = new javax.swing.JButton();
        buttonMainMenu = new javax.swing.JButton();
        toggleButtonPause = new javax.swing.JToggleButton();
        bottomInfoPanel = new javax.swing.JPanel();
        infoNextWaveLabel = new javax.swing.JLabel();
        topInfoPanel = new javax.swing.JPanel();
        moneyLabel = new javax.swing.JLabel();
        healthLabel = new javax.swing.JLabel();
        scoreLabel = new javax.swing.JLabel();
        waveLabel = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();
        loadGrid = new javax.swing.JMenuItem();
        upgradeBut = new javax.swing.JButton("<HTML><B>U<br>P<br>G<br>R<br>A<br>D<br>E</B></HTML>");
        buttonSellTower = new javax.swing.JButton("<HTML><B>S<br>E<br>L<br>L</B></HTML>");
        mainKeyAdapter mka = new mainKeyAdapter();
        this.addKeyListener(mka);
        this.setFocusable(true);
//        topInfoPanel.addKeyListener(mka);
//        topInfoPanel.setFocusable(true);
//        bottomInfoPanel.addKeyListener(mka);
//        bottomInfoPanel.setFocusable(true);
//        rightInfoPanel.addKeyListener(mka);
//        rightInfoPanel.setFocusable(true);
//        mainPanel.addKeyListener(mka);
//        mainPanel.setFocusable(true);
//        infoNextWaveLabel.addKeyListener(mka);
//        infoNextWaveLabel.setFocusable(true);
//        inGameButtonPanel.addKeyListener(mka);
//        inGameButtonPanel.setFocusable(true);
//        
        this.score = 0;
        this.cash = 250000;
        this.nextWaveText = "Are you ready?";
        this.currentWave = 0;
        this.health = 20;
        this.isMuted = false;
        

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("SNUS TD");
        setBackground(mainPanel.getBackground());
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setMaximizedBounds(getMaximizedBounds());
        setMinimumSize(new java.awt.Dimension(800, 600));
        setName("SNUS TD"); // NOI18N
//        addKeyListener(new mainKeyAdapter());
//        setFocusable(true);
        requestFocus();

        mainPanel.addMouseListener(new mainAdapter());
        ((towerdefencegame.mainPanel) mainPanel).setGui(this);
        tornPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Towers", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Verdana", 1, 11))); // NOI18N
        tornPanel.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        tornPanel.setLayout(new java.awt.GridLayout(2,3));

        toggleTower1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                toggleTower1ActionPerformed(evt);
            }
        });
//     	 toggleTower1.setIcon(new javax.swing.ImageIcon("resources/skruf.png")); // NOI18N
      	 toggleTower1.setIcon(new javax.swing.ImageIcon(getClass().getResource("../buttons/mocca.png")));
     	 toggleTower1.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("../buttons/mocca_press.png")));

      
        toggleTower1.setMaximumSize(new java.awt.Dimension(52,33));
        tornPanel.add(toggleTower1);


        toggleTower2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                toggleTower2ActionPerformed(evt);
            }
        });
   	 toggleTower2.setIcon(new javax.swing.ImageIcon(getClass().getResource("../buttons/MC.png")));
 	 toggleTower2.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("../buttons/MC_press.png")));


        tornPanel.add(toggleTower2);

        	toggleTower3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                toggleTower3ActionPerformed(evt);
            }
        });
        	 toggleTower3.setIcon(new javax.swing.ImageIcon(getClass().getResource("../buttons/gennis.png")));
         	 toggleTower3.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("../buttons/gennis_press.png")));

        tornPanel.add(toggleTower3);

        	toggleTower4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                toggleTower4ActionPerformed(evt);
            }
        });
       	 toggleTower4.setIcon(new javax.swing.ImageIcon(getClass().getResource("../buttons/skruf.png")));
     	 toggleTower4.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("../buttons/skruf_press.png")));
   
 
        tornPanel.add(toggleTower4);

        	toggleTower5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                toggleTower5ActionPerformed(evt);
            }
        });
          	 toggleTower5.setIcon(new javax.swing.ImageIcon(getClass().getResource("../buttons/gennis_xsterk.png")));
         	 toggleTower5.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("../buttons/gennis_xsterk_press.png")));
  

        tornPanel.add(toggleTower5);

        	toggleTower6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                toggleTower6ActionPerformed(evt);
            }
        });
       	 toggleTower6.setIcon(new javax.swing.ImageIcon(getClass().getResource("../buttons/skruf_xstark.png")));
     	 toggleTower6.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("../buttons/skruf_xstark_press.png")));
 
 
        tornPanel.add(toggleTower6);

        
        
        rightInfoPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Details", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Verdana", 1, 11))); // NOI18N
        rightInfoPanel.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        rightInfoPanel.setLayout(new java.awt.BorderLayout(10,0));
        detailsLabel.setText("INFO");
        detailsLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        detailsLabel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        detailsLabel.setVisible(true);
        rightInfoPanel.add(detailsLabel, java.awt.BorderLayout.CENTER);
     
       	upgradeBut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                upgradeButPerf(evt);
            }
        });
       	upgradeBut.addMouseListener(new java.awt.event.MouseListener() {

			@Override
			public void mouseClicked(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void mouseEntered(MouseEvent e) {
				// TODO Auto-generated method stub
				upgradeButFocusGained(null);
			}

			@Override
			public void mouseExited(MouseEvent e) {
				// TODO Auto-generated method stub
				upgradeButFocusLost(null); 
			}

			@Override
			public void mousePressed(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void mouseReleased(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
       		
       	});
       	upgradeBut.addFocusListener(new java.awt.event.FocusListener() {

			@Override
			public void focusGained(FocusEvent e) {
				upgradeButFocusGained(e);
			}

			@Override
			public void focusLost(FocusEvent e) {
				// TODO Auto-generated method stub
				upgradeButFocusLost(e); 
			}
       		
       	});
        
       	upgradeBut.setVerticalAlignment(javax.swing.SwingConstants.CENTER);
       	upgradeBut.setVerticalTextPosition(javax.swing.SwingConstants.CENTER);
       	upgradeBut.setVisible(false);
        rightInfoPanel.add(upgradeBut, java.awt.BorderLayout.WEST);
  
        buttonSellTower.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	buttonSellTowerPerf(evt);
            }
        });
       	buttonSellTower.addMouseListener(new java.awt.event.MouseListener() {

			@Override
			public void mouseClicked(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void mouseEntered(MouseEvent e) {
				// TODO Auto-generated method stub
				buttonSellTowerFocusGained();
			}

			@Override
			public void mouseExited(MouseEvent e) {
				// TODO Auto-generated method stub
				buttonSellTowerFocusLost(); 
			}

			@Override
			public void mousePressed(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void mouseReleased(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
       		
       	});
       	
//       	buttonSellTower.setVerticalAlignment(javax.swing.SwingConstants.TOP);
       	buttonSellTower.setVerticalTextPosition(javax.swing.SwingConstants.CENTER);
        buttonSellTower.setVisible(false);
        rightInfoPanel.add(buttonSellTower, java.awt.BorderLayout.EAST);
        
        inGameButtonPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Menu", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Verdana", 1, 11))); // NOI18N

        buttonNextWave.setText("Next wave");
        buttonNextWave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonNextWaveActionPerformed(evt);
            }
        });

        buttonMainMenu.setText("Main menu");
        buttonMainMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonMainMenuActionPerformed(evt);
            }
        });

        toggleButtonPause.setText("PAUSE");
        toggleButtonPause.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                toggleButtonPauseActionPerformed(evt);
            }
        });
       
        
       // javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
       // mainPanel.setLayout(mainPanelLayout);
       // mainPanelLayout.setAutoCreateContainerGaps(true);
        
        javax.swing.GroupLayout inGameButtonPanelLayout = new javax.swing.GroupLayout(inGameButtonPanel);
        inGameButtonPanel.setLayout(inGameButtonPanelLayout);
        inGameButtonPanelLayout.setHorizontalGroup(
            inGameButtonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(inGameButtonPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(inGameButtonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(toggleButtonPause, javax.swing.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE)
                    .addComponent(buttonNextWave, javax.swing.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE)
                    .addComponent(buttonMainMenu, javax.swing.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE)))
        );
        inGameButtonPanelLayout.setVerticalGroup(
            inGameButtonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(inGameButtonPanelLayout.createSequentialGroup()
                .addComponent(buttonNextWave, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(toggleButtonPause, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonMainMenu))
        );

        bottomInfoPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Next wave", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Verdana", 1, 11))); // NOI18N
        bottomInfoPanel.setLayout(new java.awt.BorderLayout());

        infoNextWaveLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        infoNextWaveLabel.setText("Next wave will be: Catch");
        infoNextWaveLabel.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
        bottomInfoPanel.add(infoNextWaveLabel, java.awt.BorderLayout.CENTER);

        topInfoPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Status", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Verdana", 1, 11))); // NOI18N
        topInfoPanel.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        topInfoPanel.setLayout(new java.awt.GridLayout(1, 4));

        moneyLabel.setBorder(javax.swing.BorderFactory.createTitledBorder("Money"));
        topInfoPanel.add(moneyLabel);

        healthLabel.setBorder(javax.swing.BorderFactory.createTitledBorder("Lives"));
        topInfoPanel.add(healthLabel);

        scoreLabel.setBorder(javax.swing.BorderFactory.createTitledBorder("Score"));
        topInfoPanel.add(scoreLabel);

        waveLabel.setBorder(javax.swing.BorderFactory.createTitledBorder("Wave"));
        topInfoPanel.add(waveLabel);

        jMenu1.setText("File");
        loadGrid.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, java.awt.event.InputEvent.ALT_MASK));
        loadGrid.setIcon(new javax.swing.ImageIcon(getClass().getResource("../icon.jpg"))); // NOI18N
        loadGrid.setText("Mute ze game");
        loadGrid.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	
                loadGridActionPerformed(evt);
            }
        });
        jMenu1.add(loadGrid);
        
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 557, Short.MAX_VALUE)
                    .addComponent(topInfoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 557, Short.MAX_VALUE)
                    .addComponent(bottomInfoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 557, Short.MAX_VALUE))
               // .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(tornPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 237, 237)
                    .addComponent(rightInfoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(inGameButtonPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(topInfoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                      //  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 420, Short.MAX_VALUE)
                      //  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bottomInfoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(tornPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                      //  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(rightInfoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 238, Short.MAX_VALUE)
                       // .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(inGameButtonPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))));
               // .addContainerGap())
        
        pack();
    }// </editor-fold>

    public void buttonNextWaveActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        setDetailsLabel("Next wave coming!");    
        ((towerdefencegame.mainPanel) mainPanel).newWave();
        
    }

    public void toggleButtonPauseActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        setDetailsLabel(((javax.swing.JToggleButton)inGameButtonPanel.getComponent(0)).isSelected() ?
                    "Game is paused!" :
                    ""
                );
        toggleTowerButtonPressed(-1);                
    }

    private void toggleTower1ActionPerformed(java.awt.event.ActionEvent evt) {
        toggleTowerButtonPressed(1);
    }
    private void toggleTower2ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        toggleTowerButtonPressed(2);
    }

    private void toggleTower3ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        toggleTowerButtonPressed(3);
    }

    private void toggleTower4ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        toggleTowerButtonPressed(4);
    }

    private void toggleTower5ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        toggleTowerButtonPressed(5);
    }

    private void toggleTower6ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        toggleTowerButtonPressed(6);
    }


    public void buttonMainMenuActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        setDetailsLabel("Main menu");
        
  }
    
    private void loadGridActionPerformed(java.awt.event.ActionEvent evt) {
        setMute(true);
        if(((towerdefencegame.mainPanel) mainPanel).getMusic() != null)
        ((towerdefencegame.mainPanel) mainPanel).getMusic().stop();
    }
    
    public void upgradeButPerf(java.awt.event.ActionEvent evt) {
    	int c = getSelectedMaintower().getUpgradeCost();
    	if(getCash()-c < 0) 
    	setDetailsLabel("Not enough money!");
    	else {
    	setDetailsLabel(getSelectedMaintower().upgrade());
    	this.setCash(getCash()-c);
    	}
    }
    public void upgradeButFocusGained(FocusEvent evt) {
    	setDetailsLabel(getSelectedMaintower().updateToString());
    }
    public void upgradeButFocusLost(FocusEvent evt) {
    	setDetailsLabel(getSelectedMaintower() != null ? getSelectedMaintower().toString() : "");
    }
    public void buttonSellTowerPerf(java.awt.event.ActionEvent evt) {
    	int c = getSelectedMaintower().getSellPrice();
    	int y = getSelectedMaintower().getPositionY();
    	int x = getSelectedMaintower().getPositionX();
        int LEFT_STARTINGPOSITION = (mainPanel.getWidth()/2)-((((towerdefencegame.mainPanel) mainPanel).getCellSize()*GRID_COLS)/2);
        x -= LEFT_STARTINGPOSITION;
		int TOP_STARTINGPOSITION = (mainPanel.getHeight()/2)-((((towerdefencegame.mainPanel) mainPanel).getCellSize()*GRID_ROWS)/2);     		
		y -= TOP_STARTINGPOSITION;	
        int cCol = x / ((towerdefencegame.mainPanel) mainPanel).getCellSize();
        int cRow = y / ((towerdefencegame.mainPanel) mainPanel).getCellSize();
        ((towerdefencegame.mainPanel)mainPanel).setGrid(cRow,cCol, BOARD_GRAS);
    	setCash(getCash()+c);
    	buttonSellTower.setVisible(false);
    	upgradeBut.setVisible(false);
    	setDetailsLabel("Tower sold for: "+c);
    }
    public void buttonSellTowerFocusGained() {
    	setDetailsLabel("<HTML>Sell price: "+getSelectedMaintower().getSellPrice()+"</HTML>");
    }
    public void buttonSellTowerFocusLost() {
    	setDetailsLabel(getSelectedMaintower() != null ? getSelectedMaintower().toString() : "");
    }

    

    /**
    * @author Sindre Haaland
    * @param torn Number of the tower / toggle-button clicked
    */
    protected void toggleTowerButtonPressed(int torn) {
    	upgradeBut.setVisible(false);
    	buttonSellTower.setVisible(false);
    	
        for(int i=0; i<tornPanel.getComponentCount(); i++) {
            if(torn-1 != i) {
	            ((javax.swing.JToggleButton)tornPanel.getComponent(i)).setSelected(false);
            }
            else {
                setDetailsLabel(((javax.swing.JToggleButton)tornPanel.getComponent(i)).isSelected() ?
                    "<HTML><B>Tower</B> #"+(i+1)+"'s information:<br><br>"+toggleTower1.getWidth()+ " "+toggleTower1.getHeight()+"</html>" :
                    ""
                );
                ((towerdefencegame.mainPanel) mainPanel).setSelected(((javax.swing.JToggleButton)tornPanel.getComponent(i)).isSelected() ? torn : -1);
            }
        }
    }
    public void setToggleTowerButton(int torn) {
    	toggleTowerButtonPressed(torn);
    	((towerdefencegame.mainPanel) mainPanel).setSelected(torn);
        ((javax.swing.JToggleButton)tornPanel.getComponent(torn-1)).setSelected(true);

    }
    public int getSelectedTower() {
        for(int i=0; i<tornPanel.getComponentCount(); i++) {
            if(((javax.swing.JToggleButton)tornPanel.getComponent(i)).isSelected()) return (i+1);
            }
        return -1;
    }

    protected void setDetailsLabel(String tekst) {
        if(!((javax.swing.JToggleButton)inGameButtonPanel.getComponent(0)).isSelected() || tekst == "Game is paused!")
        detailsLabel.setText(tekst);
    }
    public void setTowerSelected(tower.maintower tower) {
    	this.selectedTower = tower;
    	if(tower != null) {
    	upgradeBut.setVisible(true);
    	buttonSellTower.setVisible(true);
    	}
    	else {
    		upgradeBut.setVisible(false);
    		buttonSellTower.setVisible(false);
    	}
    }
    public tower.maintower getSelectedMaintower() {
    	return this.selectedTower;
    }
    public int getScore() {
    	return this.score;
    }
    public int getCash(){
    	return this.cash;
    }
    public int getCurrentWave() {
    	return this.currentWave;
    }
    public int getHealth() {
    	return this.health;
    }
    public void setNextWaveString(String txt) {
    	this.nextWaveText = txt;
    }
    public void updateVarHolders() {
    	scoreLabel.setText(""+getScore());
    	healthLabel.setText(""+getHealth());
    	moneyLabel.setText(""+getCash());
    	waveLabel.setText(""+getCurrentWave() +" (Creeps Left: " + getCreepsLeft() +")");
    	infoNextWaveLabel.setText(this.nextWaveText);
//    	bottomInfoPanel.repaint();
//    	topInfoPanel.repaint();

    }
    public void setScore(int s) {
    	 this.score = s;
    }
    public void setCash(int c){
    	 this.cash = c;
    }
    public void setCurrentWave(int w) {
    	 this.currentWave = w;
    }
    public void setHealth(int hp) {
    	 this.health = hp;
    }
    
    public int getCreepsLeft(){
    	return this.creepsLeft;
    }
    
    public void setCreepsLeft(int i){
    	this.creepsLeft=i;
    }
    public boolean isMuted() {
    	return this.isMuted;
    }
    public void setMute(boolean b) {
    	this.isMuted = b;
    }
  
 
    
    // Variables declaration - do not modify
    private javax.swing.JPanel bottomInfoPanel;
    private javax.swing.JButton buttonMainMenu;
    private javax.swing.JButton buttonNextWave;
    private javax.swing.JButton buttonSellTower;
    private javax.swing.JLabel detailsLabel;
    private javax.swing.JLabel healthLabel;
    private javax.swing.JPanel inGameButtonPanel;
    private javax.swing.JLabel infoNextWaveLabel;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuItem loadGrid;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private JPanel mainPanel;
    private javax.swing.JLabel moneyLabel;
    private javax.swing.JPanel rightInfoPanel;
    private javax.swing.JLabel scoreLabel;
    private javax.swing.JToggleButton toggleButtonPause;
    private javax.swing.JToggleButton toggleTower1;
    private javax.swing.JToggleButton toggleTower2;
    private javax.swing.JToggleButton toggleTower3;
    private javax.swing.JToggleButton toggleTower4;
    private javax.swing.JToggleButton toggleTower5;
    private javax.swing.JToggleButton toggleTower6;
    private javax.swing.JButton upgradeBut;
    private tower.maintower selectedTower;
    private javax.swing.JPanel topInfoPanel;
    protected javax.swing.JPanel tornPanel;
    private javax.swing.JLabel waveLabel;
    
    private int score;
    private int cash;
    private String nextWaveText;
    private int currentWave;
    private int health;
    private boolean isMuted;
    private int creepsLeft;
   
    class mainKeyAdapter extends KeyAdapter implements constantsUsed {
   
    	public void keyPressed(KeyEvent e) {
    		if(e.getKeyCode() == KeyEvent.VK_ESCAPE) {
    			toggleTowerButtonPressed(-1);
    			((towerdefencegame.mainPanel) mainPanel).setSelected(-1);
    			setDetailsLabel("");
    		}
    		else if(e.getKeyCode() == KeyEvent.VK_ALT){
    			// loop alle creeps, isSelected = true
    			// loop alle torn, isSelected = true
    			tower.maintower[][] tow = ((towerdefencegame.mainPanel)mainPanel).getGrid();
    			for(int y=0; y<tow.length; y++) 
    				for (int x=0; x<tow[0].length; x++) 
    					tow[y][x].setSelected(true);
    			
    			for (Creep creep : ((towerdefencegame.mainPanel)mainPanel).getCreeps()) 
					creep.setSelected(true);
				
    		}
    	}
    	public void keyReleased(KeyEvent e) {
    		if(e.getKeyCode() == KeyEvent.VK_ALT) {
    			tower.maintower[][] tow = ((towerdefencegame.mainPanel)mainPanel).getGrid();
    			for(int y=0; y<tow.length; y++) 
    				for (int x=0; x<tow[0].length; x++) 
    					tow[y][x].setSelected(false);
    			
    			for (Creep creep : ((towerdefencegame.mainPanel)mainPanel).getCreeps()) 
					creep.setSelected(false);
				
    		}
    	}
    	
    	public void keyTyped(KeyEvent e) {
    		if(e.getKeyChar()=='1') {
    			setToggleTowerButton(1);
    		}
    		else if(e.getKeyChar()=='2') {
    			setToggleTowerButton(2);
    		}
    		else if(e.getKeyChar()=='3') {
    			setToggleTowerButton(3);
    		}
    		else if(e.getKeyChar()=='4') {
    			setToggleTowerButton(4);
    		}
    		else if(e.getKeyChar()=='5') {
    			setToggleTowerButton(5);
    		}
    		else if(e.getKeyChar()=='6') {
    			setToggleTowerButton(6);
    		}
    		else if(e.getKeyChar()== '+') {
      			tower.maintower[][] tow = ((towerdefencegame.mainPanel)mainPanel).getGrid();
    			for(int y=0; y<tow.length; y++) 
    				for (int x=0; x<tow[0].length; x++) 
    					tow[y][x].setSelected(true);
    			
    			for (Creep creep : ((towerdefencegame.mainPanel)mainPanel).getCreeps()) 
					creep.setSelected(true);
				
    		}
    		else if(e.getKeyChar() == '-') {
      			tower.maintower[][] tow = ((towerdefencegame.mainPanel)mainPanel).getGrid();
    			for(int y=0; y<tow.length; y++) 
    				for (int x=0; x<tow[0].length; x++) 
    					tow[y][x].setSelected(false);
    			
    			for (Creep creep : ((towerdefencegame.mainPanel)mainPanel).getCreeps()) 
					creep.setSelected(false);
    		}
    	}
    	
    }
    
    class mainAdapter extends MouseAdapter implements constantsUsed {  	
    	private void correctCost() {
			switch( getSelectedTower()) {
               case 1:
            	   setCash(getCash()+MOCCA_COST);
            	   break;
               case 2:
            	   setCash(getCash()+MC_COST);
            	   break;
               case 3: 
            	   setCash(getCash()+GENNIS_COST);
            	   break;
               case 4: 
            	   setCash(getCash()+SKRUF_ORGINAL_COST);
            	   break;
               case 5:
            	   setCash(getCash()+GENNIS_XSTERK_COST);
            	   break;
               case 6:
            	   setCash(getCash()+SKRUF_XSTERK_COST);
            	   break;
               }
		}
        public void mousePressed(MouseEvent e) {
        	int y = getMouseY(e);
            int x = getMouseX(e);         
    	
    		if(y>0 && x>0) {
                int cCol = x / ((towerdefencegame.mainPanel) mainPanel).getCellSize();
                int cRow = y / ((towerdefencegame.mainPanel) mainPanel).getCellSize();
                
                if(((towerdefencegame.mainPanel) mainPanel).getSelected() == -1) {
                	// Select tower
                	if(((towerdefencegame.mainPanel)mainPanel).getGrid(cRow,cCol) != null && ((towerdefencegame.mainPanel)mainPanel).getGrid(cRow,cCol).getTowerType() != BOARD_GRAS &&((towerdefencegame.mainPanel)mainPanel).getGrid(cRow,cCol).getTowerType() != BOARD_ROAD ) {
                		// Add upgrade buttons
                	setTowerSelected(((towerdefencegame.mainPanel)mainPanel).getGrid(cRow,cCol));
                	((towerdefencegame.mainPanel)mainPanel).setSelectedTowerX(cCol);
                	((towerdefencegame.mainPanel)mainPanel).setSelectedTowerY(cRow);
                   	setDetailsLabel(((towerdefencegame.mainPanel)mainPanel).getGrid(cRow,cCol).toString());     
                	}
                	else { 
                		setDetailsLabel("");
                		//toggleTowerButtonPressed(-1);
                		setTowerSelected(null);
                    	((towerdefencegame.mainPanel)mainPanel).setSelectedTowerX(-1);
                    	((towerdefencegame.mainPanel)mainPanel).setSelectedTowerY(-1);
     
                	}
                }
                else {
	                
	                // Might get some out of bounds in the top corner
	                try{
	                	
               switch( getSelectedTower()) {
	               case 1:
	            	   setCash(getCash()-MOCCA_COST);
	            	   break;
	               case 2:
	            	   setCash(getCash()-MC_COST);
	            	   break;
	               case 3: 
	            	   setCash(getCash()-GENNIS_COST);
	            	   break;
	               case 4: 
	            	   setCash(getCash()-SKRUF_ORGINAL_COST);
	            	   break;
	               case 5:
	            	   setCash(getCash()-GENNIS_XSTERK_COST);
	            	   break;
	               case 6:
	            	   setCash(getCash()-SKRUF_XSTERK_COST);
	            	   break;
	               }
               	  if(getCash()>-1) {
               	 	 if(!((towerdefencegame.mainPanel) mainPanel).setGrid(cRow, cCol, ((towerdefencegame.mainPanel) mainPanel).getSelected())) {
               	 		 correctCost();    	
               	 		 setTowerSelected(((towerdefencegame.mainPanel)mainPanel ).getGrid(((towerdefencegame.mainPanel)mainPanel).getSelectedTowerY(), ((towerdefencegame.mainPanel)mainPanel).getSelectedTowerX()));
               	       	 setDetailsLabel(((towerdefencegame.mainPanel)mainPanel).getGrid(cRow,cCol).toString());
                        
               	 		 if(getSelectedMaintower().getTowerType()==BOARD_GRAS || getSelectedMaintower().getTowerType()==BOARD_ROAD) {
               	 			 setDetailsLabel("");
               	 			 upgradeBut.setVisible(false);
               	 			 buttonSellTower.setVisible(false);
               	 		 }
               	 	 }
               	  
               	  }
               	  else {
               		  correctCost();
               		  setDetailsLabel("Not enough money!");
               	  }
	                }catch(Exception exc) { correctCost(); }     
	    			}
    			}
    		
    	
    		// set creep info
    		for (Creep creep : ((towerdefencegame.mainPanel) mainPanel).getCreeps()) {
   				if(creep.getBounds().contains(e.getPoint())) {
   					setDetailsLabel(creep.toString());
   					 
   				}
   			}
               
        	}
    		private int getMouseY(MouseEvent e) {
    			int y = e.getY();
    			int TOP_STARTINGPOSITION = (mainPanel.getHeight()/2)-((((towerdefencegame.mainPanel) mainPanel).getCellSize()*GRID_ROWS)/2);     		
    			y -= TOP_STARTINGPOSITION;	
    			return y;
    		}
    		private int getMouseX(MouseEvent e) {
    	        int x = e.getX();           
    	        int LEFT_STARTINGPOSITION = (mainPanel.getWidth()/2)-((((towerdefencegame.mainPanel) mainPanel).getCellSize()*GRID_COLS)/2);
    	        x -= LEFT_STARTINGPOSITION;
    	        return x;
    		}
    }
    
    
}
